//
//  ViewController.m
//  UI20_礼物说
//
//  Created by 石美妮 on 16/1/5.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "ViewController.h"
#import "NetWorkHandler.h"
#import "Model.h"
#import "MyTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "ScrollModel.h"
#import "CollectionCell.h"
#import "collectionModel.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic, strong) NSMutableArray *dataArr;// 保存tableView中的数据
@property(nonatomic, strong) NSMutableArray *scrollArr; // 保存 scrollArr的数据
@property(nonatomic, strong) UIPageControl *page;
@property(nonatomic, strong) NSTimer *time;
@property(nonatomic, strong) NSMutableArray *CollectionArr; // 保存 collectionView中的数据
@property(nonatomic, strong) UICollectionView *collection;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"礼物说";
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    // 夜间模式
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    // 左侧按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"2"] style:UIBarButtonItemStyleDone target:self action:@selector(enter)];
    // 设置左侧按钮颜色
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    // 右侧按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"3"] style:UIBarButtonItemStylePlain target:self action:@selector(LookFor)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    [self creatTableView];
    // cell 获取数据
    [self dataHandler];
    // 轮播图获取数据
    [self scrollDataHandler];
    [self creatCollectionView];
    
}


#pragma mark - 创建tableView和ScrollView
- (void)creatTableView
{
   self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    // 设置代理人
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"cell"];
    // 留空间
   // self.tableView.contentInset = UIEdgeInsetsMake(250, 0, 0, 0);
    // 预留头部空间
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 260)];
    // 创建一个ScrollView
   self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 375, 150)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.tableView addSubview:self.scrollView];
    self.scrollView.delegate = self;
    // 整页翻动
    _scrollView.pagingEnabled = YES;
    // 设置实际内容大小
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 6, 100);
}

#pragma mark - 对tableView进行数据处理
- (void)dataHandler
{
    NSString *str = @"http://api.liwushuo.com/v2/channels/101/items?limit=20&ad=2&gender=1&offset=0&generation=2";
    [NetWorkHandler GETWithURL:str completion:^(id result) {
        // 将数组变成数组+对象
        self.dataArr = [Model modelHandlerWithArray:result[@"data"][@"items"]];
        // NSLog(@"%@", _dataArr);
        [_tableView reloadData];
        
    }];
    
}
#pragma mark - 轮播图数据处理
- (void)scrollDataHandler
{
    NSString *str = @"http://api.liwushuo.com/v2/banners";
    
    [NetWorkHandler GETWithURL:str completion:^(id result) {
        NSArray *arr = result[@"data"][@"banners"];
        self.scrollArr = [ScrollModel modelHandlerWithArray:arr];
        for (int i = 0; i < _scrollArr.count; i++) {
            UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, 150)];
            [self.scrollView addSubview:img];
            ScrollModel *m =  _scrollArr[i];
            [img sd_setImageWithURL:[NSURL URLWithString:m.image_url]];
        }
        
        // 添加最后一张图片
        UIImageView *lastImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width * 6, 0, self.view.frame.size.width, 150)];
        ScrollModel *model = _scrollArr[0];
        [ lastImage sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
        // 添加到_scrollView的末尾
        [_scrollView addSubview:lastImage];
        
        self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 120, 200, 20)];
        // self.page.backgroundColor = [UIColor blackColor];
        self.page.numberOfPages = _scrollArr.count;
        self.page.center = CGPointMake(self.scrollView.center.x, self.page.center.y);
        [self.tableView addSubview:self.page];
        [self.page addTarget:self action:@selector(page:) forControlEvents:UIControlEventTouchUpInside];
      self.time = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(roll:) userInfo:nil repeats:YES];
        
        [_tableView reloadData];
    }];
}

#pragma mark - CollctionView的创建
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 行间距
    layout.minimumInteritemSpacing = 1;
    // 列间距不设了
    layout.itemSize = CGSizeMake((600 - 5) / 6, 100);
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 160, self.view.frame.size.width, 100) collectionViewLayout:layout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self.tableView addSubview:self.collection];
    self.collection.backgroundColor = [UIColor whiteColor];
    
    [self.collection registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"cell"];
    
    NSString *str = @"http://api.liwushuo.com/v2/secondary_banners?gender=1&generation=2";
    [NetWorkHandler GETWithURL:str completion:^(id result) {
        self.CollectionArr = [collectionModel modelHandlerWithArray:result[@"data"][@"secondary_banners"]];
        [_collection reloadData];
        
    }];

}
#pragma mark - collectionView必须实现的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 6;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
   // cell.backgroundColor = [UIColor redColor];
    collectionModel *model = _CollectionArr[indexPath.row];
    [cell.img sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
    return cell;
}

#pragma mark - 定时器
- (void)roll:(UIPageControl *)page
{
    if (_page.currentPage == 5) {
        
        _page.currentPage = 0;
        [_scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * 6, 0) animated:YES];
        
        
    }else
    {
        if (_page.currentPage == 0) {
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    _page.currentPage++;
    [_scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * _page.currentPage, 0) animated:YES];
    }
}

// scrollView 跟着 page走
- (void)page:(UIPageControl *)pag
{
    self.scrollView.contentOffset = CGPointMake(pag.currentPage * self.scrollView.frame.size.width, 0);
    
}
// page 跟着scrollView 走
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.page.currentPage = self.scrollView.contentOffset.x / self.scrollView.frame.size.width;
}
#pragma mark - 开始拖拽,停止timmer
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_time invalidate];
    _time = nil;
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
   
        self.time = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(roll:) userInfo:nil repeats:YES];

}

#pragma mark - tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    Model *m = _dataArr[indexPath.row];
    cell.titleLabel.text = m.title;
    [cell.img sd_setImageWithURL:[NSURL URLWithString:m.cover_image_url]];
    cell.likeLabel.text = m.likes_count.stringValue;
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170;
}
- (void)enter
{
    NSLog(@"登陆");
}
- (void)LookFor
{
    NSLog(@"搜索");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
